package Sort;

public class sort4 {
    //堆排序
    public static void main(String[] args) {
        int[] arr = {10, 5, 21, 6, 7, 2, 9, 11, 3, 1};
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
        System.out.println();
        heapSort(arr);
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
    }

    private static void heapSort(int[] arr) {
        buildHeap(arr);
        int end = arr.length-1;
        while (end>0){
            swap(arr,0,end);
            shiftDown(arr,0,end);
            end--;
        }
    }

    private static void buildHeap(int[] arr) {
        //找到最后一棵子树的根结点
        for (int parent = (arr.length - 1 - 1) / 2; parent >= 0; parent--) {
            shiftDown(arr, parent, arr.length);
        }
    }

    private static void shiftDown(int[] arr, int parent, int length) {
        //左子节点
        int child = 2 * parent + 1;
        while (child <= length - 1) {
            //比较出左右子节点最大值
            if (child + 1 < length && arr[child + 1] > arr[child]) {
                child++;
            }
            if(arr[child]>arr[parent]){
                swap(arr, parent, child );
                parent = child;
                child = 2 * parent + 1;
            }
            else {
                break;
            }

        }
    }

    public static void swap(int[] arr, int i, int j) {
        int tmp = arr[j];
        arr[j] = arr[i];
        arr[i] = tmp;
    }
}
